package com.mq.redis.queue.executor;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.springframework.stereotype.Controller;

import com.mq.model.WorksPoolConfig;

/**
 * ack线程池
 * @author wenfei
 *
 */
@Controller
public class RedisQueueAckExecutor {
	
/*	private ScheduledThreadPoolExecutor scheduledThreadPoolExecutor;
	public RedisQueueAckExecutor() {
		scheduledThreadPoolExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(Integer.MAX_VALUE);
	}
	
	
	public RedisQueueAckExecutor(AckPoolConfig ackPoolConfig) {
		if (ackPoolConfig.isCustom()) {
			scheduledThreadPoolExecutor = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(ackPoolConfig.getCorePoolSize());
		}
	}
	
	
	public ScheduledThreadPoolExecutor getScheduledThreadPoolExecutor(){
		return scheduledThreadPoolExecutor;
	}*/
	
	
	public ExecutorService executorService;

	public RedisQueueAckExecutor() {
		// 默认构造采用缓存线程池
		this.executorService = Executors.newCachedThreadPool();
	}

	public RedisQueueAckExecutor(WorksPoolConfig config) {
		if (config.isCustom()) {
			BlockingQueue<Runnable> queue = null;
			if (config.getWorkQueue() > 0) {
				queue = new LinkedBlockingQueue<Runnable>(config.getWorkQueue()); // 可能根据机器jvm配置定义
																					
			} else {
				// 没有配置情况下, 默认采用有序无界队列
				queue = new LinkedBlockingQueue<Runnable>();
			}
			// 配置线程池信息
			this.executorService = new ThreadPoolExecutor(
					// 默认大小                         // 最大连接数 
					config.getCorePoolSize(), config.getMaximumPoolSize(),
					// 回收时间                                           // 回收时间单位            // 采用队列
					config.getKeepAliveTime(), TimeUnit.SECONDS, queue,
					// 拒绝策略，任务队列满后，新的任务将被丢弃，并抛出异常
					new ThreadPoolExecutor.AbortPolicy()
			);
		} else {
			this.executorService = Executors.newCachedThreadPool();
		}
	}

	/*
	 * 创建线程，对线程处理事件
	 */
	public void execute(Runnable runnable) {
		executorService.execute(runnable);
	}

	
	
	
	
}
